﻿<%@ Page Language="C#" AutoEventWireup="true" %>

<% 
    //公众平台上开发者设置的token, appID, EncodingAESKey
    string sToken = weixin.api.WXConfig.sToken;
    string sAppID = weixin.api.WXConfig.sAppID;
    string sEncodingAESKey = weixin.api.WXConfig.sEncodingAESKey;

    System.IO.Stream sw = Request.InputStream;
    if (sw.Length > 0)
    {
        Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID);

        byte[] buffer = new byte[sw.Length];
        sw.Read(buffer, 0, buffer.Length);
        sw.Close();

        //System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath("~/log.txt"));
        //System.IO.FileStream fs = fi.OpenWrite();
        //fs.Seek(fs.Length, System.IO.SeekOrigin.Begin);
        //fs.Write(buffer, 0, buffer.Length);

        string sReqTimeStamp = Request.QueryString["timestamp"];
        string sReqNonce = Request.QueryString["nonce"];
        string encrypt_type = Request.QueryString["encrypt_type"];
        string sReqMsgSig = Request.QueryString["msg_signature"];
        string sReqData = System.Text.Encoding.UTF8.GetString(buffer);
        //string str = string.Format("timestamp:{0},nonce:{1},encrypt_type:{2},msg_signature:{3}", timestamp, nonce, encrypt_type, msg_signature);
        //fs.Seek(fs.Length, System.IO.SeekOrigin.Begin);
        //buffer = System.Text.Encoding.UTF8.GetBytes(str);
        //fs.Write(buffer, 0, buffer.Length);

        //fs.Flush();
        //fs.Close();

        string sMsg = "";  //解析之后的明文
        int ret = 0;
        ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg);
        if (ret != 0)
        {
            Response.Write("ERR: Decrypt fail, ret: " + ret);
            return;
        }
        else
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(sMsg);
            System.Xml.XmlNode node = doc.FirstChild;
            if (node != null && node["InfoType"].InnerText == "component_verify_ticket")
            {
                string ComponentVerifyTicket = node["ComponentVerifyTicket"].InnerText;
                string filepath = HttpContext.Current.Server.MapPath("/Cache/ComponentVerifyTicket");
                if (System.IO.File.Exists(filepath))
                {
                    System.IO.File.Delete(filepath);
                }
                System.IO.File.AppendAllText(filepath, ComponentVerifyTicket);
            }
        }
    }

    Response.Clear();
    Response.Write("success");
%>